import { Permission } from './modules/user/entities/Permission';
import { Role } from './modules/user/entities/Role';
import { User } from './modules/user/entities/User';
import { Module, ValidationPipe } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { UserModule } from './modules/user/user.module';
import { RedisModule } from './modules/redis/redis.module';
import { EmailModule } from './modules/email/email.module';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { APP_GUARD, APP_PIPE } from '@nestjs/core';
import { JwtModule } from '@nestjs/jwt';
import { LoginGuard } from './common/guard/login.guard';
import { PermissionGuard } from './common/guard/permission.guard';
import { MeetingRoomModule } from './modules/meeting-room/meeting-room.module';
import { MeetingRoom } from './modules/meeting-room/entities/meeting-room.entity';

@Module({
    imports: [
        ConfigModule.forRoot({
            isGlobal: true,
            envFilePath: '.env'
        }),
        TypeOrmModule.forRootAsync({
            useFactory(configService: ConfigService) {
                return {
                    type: 'mysql',
                    host: configService.get('mysql_server_host'),
                    port: configService.get('mysql_server_port'),
                    username: configService.get('mysql_server_username'),
                    password: configService.get('mysql_server_password'),
                    database: configService.get('mysql_server_database'),
                    synchronize: true,
                    logging: false,
                    entities: [User, Role, Permission, MeetingRoom],
                    poolSize: 10,
                    connectorPackage: 'mysql2',
                    extra: {
                        authPlugin: 'sha256_password',
                    },
                }
            },
            inject: [ConfigService]
        }),
        JwtModule.registerAsync({
            global: true,
            useFactory(configService: ConfigService) {
                return {
                    secret: configService.get('jwt_secret'),
                    signOptions: {
                        expiresIn: '30m'//默认30分钟
                    }
                }
            },
            inject: [ConfigService]
        }),
        UserModule,
        RedisModule,
        EmailModule,
        MeetingRoomModule,
    ],
    providers: [
        // 全局管道有注册顺序之分，同一种类型，在前面的先执行
        {
            provide: APP_PIPE,
            useClass: ValidationPipe
        },
        {
            provide: APP_GUARD,
            useClass: LoginGuard
        },
        {
            provide: APP_GUARD,
            useClass: PermissionGuard
        },


    ]
})
export class AppModule { }
